package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cloudfun.campusshare.common.model.dto.BillCreateDTO;
import com.cloudfun.campusshare.common.model.vo.BillListVO;
import com.cloudfun.campusshare.common.response.PageResult;
import com.cloudfun.campusshare.common.security.AuthenticationHolder;
import com.cloudfun.campusshare.entity.BillEntity;
import com.cloudfun.campusshare.repo.BillRepo;
import com.cloudfun.campusshare.service.BillService;
import com.cloudfun.campusshare.util.AmountUtil;
import com.cloudfun.campusshare.util.DateUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/4/17 15:01
 * @description :
 */
@Service
public class BillServiceImpl implements BillService {

    @Resource
    private BillRepo billRepo;

    @Override
    public void create(BillCreateDTO createDTO) {
        BillEntity billEntity = new BillEntity();
        BeanUtil.copyProperties(createDTO, billEntity);
        billRepo.save(billEntity);
    }

    @Override
    public PageResult<BillListVO> search(Pageable pageable) {
        pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(Sort.Direction.DESC, "createTime"));
        Page<BillEntity> result = billRepo.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(criteriaBuilder.equal(root.get("userId"), AuthenticationHolder.getUserId()));
            Predicate[] predicates = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicates));
        }, pageable);
        List<BillListVO> billListVOList = result.getContent().stream()
                .map(billEntity -> {
                    BillListVO billListVO = new BillListVO();
                    BeanUtil.copyProperties(billEntity, billListVO, "amount", "createTime");
                    billListVO.setAmount(AmountUtil.amountRoundStr(billEntity.getAmount(), 2));
                    billListVO.setCreateTime(DateUtil.DATE_TIME_FORMATTER.format(billEntity.getCreateTime()));
                    return billListVO;
                }).collect(Collectors.toList());
        return new PageResult<>(result.getTotalElements(), billListVOList);
    }
}
